<template>
  <div class="xtx-checkbox" @click="toggleChecked">
    <!-- 选中小图标 -->
    <i v-if="checked" class="iconfont icon-checked"></i>
    <!-- 未选中小图标 -->
    <i v-else class="iconfont icon-unchecked"></i>

    <!-- 自定义文字 -->
    <!-- <span>是否有图</span> -->
    <!-- 插槽 -->
    <slot></slot>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
export default {
  name: 'XtxCheckBox',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    }
  },
  setup (props, { emit }) {
    const checked = ref(false)

    const toggleChecked = () => {
      checked.value = !checked.value

      emit('update:modelValue', checked.value)
    }

    watch(() => props.modelValue,
      (newVal) => {
        // console.log(newVal)
        // 传过来的是reactive
        checked.value = newVal
      }, {
        immediate: true// 第一次modelValue没有变化的值仍然赋值给checked
      })

    return { checked, toggleChecked }
  }
}
</script>
<style scoped lang="less">
.xtx-checkbox {
  display: inline-block;
  margin-right: 2px;
  .icon-checked {
    color: @xtxColor;
    // 指定元素之后的相邻兄弟元素
    ~ span {
      color: @xtxColor;
    }
  }
  i {
    position: relative;
    top: 1px;
  }
  span {
    margin-left: 2px;
  }
}
</style>
